package com.lagou.guavademo.Service;

import com.lagou.guavademo.Dao.Mapper.PositionMapper;
import com.lagou.guavademo.Dao.Pojo.Position;
import com.lagou.guavademo.cache.PositionGuava;
import com.lagou.guavademo.cache.PositionRedis;
import com.lagou.guavademo.cache.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import redis.clients.jedis.exceptions.JedisConnectionException;

import java.util.concurrent.ExecutionException;

@Service
public class PositionService {

    @Autowired
    private PositionMapper positionMapper;

    @Autowired
    private PositionGuava positionGuava;

    @Autowired
    private PositionRedis positionRedis;

    public String getById(int id) throws ExecutionException {
        String result;
        try {
            result = PositionRedis.getPosition(id);
        } catch (JedisConnectionException e) {
            result = positionGuava.getById(String.valueOf(id));
        }
        return result;
//        return positionMapper.findById(id);
    }

    public void addNew(Position position) {
        // 写入数据库
        positionMapper.insertPosition(position);
        // 写入redis缓存
        positionRedis.addPosition(position);
    }
}
